﻿using NPOI.HSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ET.ScoreTeacherClient.Views;

using System.Windows.Forms;
using UserControl = System.Windows.Controls.UserControl;
using System.Diagnostics;
using System.Runtime.InteropServices;
using ET_DbCommon.Model;
using ET_DbCommon.DAL;

namespace ET.ScoreTeacherClient
{
    /// <summary>
    /// MainWindowNew.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindowNew : Window
    {

        public MainWindowNew()
        {
            InitializeComponent();
        }

        private System.Windows.Forms.NotifyIcon notifyIcon;
        public static OperateItemModel operateitem = new OperateItemModel();
        public List<OperateItemModel> OperateitemList = new List<OperateItemModel>();


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //this.paperName.Text = System.Configuration.ConfigurationManager.AppSettings["CompetitionDbConnStr"].Split('.')[3].Split(';')[0] + ":" + System.Configuration.ConfigurationManager.AppSettings["LineName"];
                this.paperName.Text = System.Configuration.ConfigurationManager.AppSettings["SoftwareName"];
                this.PaperManager.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent, this.PaperManager));
                this.PaperManager.IsSelected = true;
                Task.Run(() => { this.Read(); });
                this.StartNotify();
                MainWindowNew.CurMainWindow = this;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void UpdateFinishStepPost()
        {
            var steps = ET_DbCommon.DAL.Paper_TestQuestion_Task_StepDAL.GetMyPaper_TestQuestion_Task_StepModelByOperationID(165);
            int count = 0;
            foreach (var step in steps)
            {
                count++;
                var task = ET_DbCommon.DAL.Paper_TestQuestion_TaskDAL.GetByID(step.TaskId);
                if (task != null)
                {
                    var test = ET_DbCommon.DAL.Paper_TestQuestionDAL.GetMyPaper_TestQuestionModel(task.TestId);
                    if (test != null)
                    {
                        step.RoleId = test.Roles;
                    }
                }
            }
            ET_DbCommon.DAL.Paper_TestQuestion_Task_StepDAL.Update(steps);

        }

        #region 启动托盘

        /// <summary>
        /// 启动托盘
        /// </summary>
        private void StartNotify()
        {
            this.notifyIcon = new System.Windows.Forms.NotifyIcon();
            this.notifyIcon.BalloonTipText = "系统监控中... ...";
            this.notifyIcon.ShowBalloonTip(2000);
            this.notifyIcon.Text = "系统监控中... ...";

            this.notifyIcon.Icon = new System.Drawing.Icon(@"teacher.ico");
            this.notifyIcon.Visible = true;
            this.notifyIcon.DoubleClick += notifyIcon_DoubleClick;
            //打开菜单项
            System.Windows.Forms.MenuItem open = new System.Windows.Forms.MenuItem("打开");
            open.Click += new EventHandler(Show);
            //退出菜单项
            System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("退出");
            exit.Click += new EventHandler(Close);
            //关联托盘控件
            System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[]
            {open, exit};
            notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen);

            this.notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler((o, e) =>
            {
                if (e.Button == System.Windows.Forms.MouseButtons.Left)
                    this.WindowState = WindowState.Normal;
                //this.Show(o, e);
            });
            this.ShowInTaskbar = false;
        }

        void notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            this.Visibility = System.Windows.Visibility.Visible;
            this.ShowInTaskbar = true;
            this.WindowState = WindowState.Normal;
            this.Activate();
        }

        private void Show(object sender, EventArgs e)
        {
            this.Visibility = System.Windows.Visibility.Visible;
            this.ShowInTaskbar = true;
            this.WindowState = WindowState.Normal;
            this.Activate();
        }

        private void Hide(object sender, EventArgs e)
        {
            this.ShowInTaskbar = false;
            this.Visibility = System.Windows.Visibility.Hidden;
        }

        private void Close(object sender, EventArgs e)
        {
            App.Current.Shutdown();
        }

        #endregion
        public static bool MissionChecked = true;

        private Dictionary<string, UserControl> Modules { get; set; } = new Dictionary<string, UserControl>();
        public bool IsInit { get; set; } = true;
        private bool m_ExamState;
        public bool ExamState
        {
            get { return m_ExamState; }
            set
            {
                m_ExamState = value;
            }
        }

        public static Dictionary<int, List<DeviceModel>> DeviceList = new Dictionary<int, List<DeviceModel>>();
        public static Dictionary<int, List<DeviceModel>> DeviceListFromLine = new Dictionary<int, List<DeviceModel>>();
        public static List<DeviceModel> temp = new List<DeviceModel>();
        public static Dictionary<int, List<Device_StateModel>> DeviceStateList = new Dictionary<int, List<Device_StateModel>>();
        public static PaperModel ChooseTestPaper { get; set; }
        public static MainWindowNew CurMainWindow { get; set; }
        private void OnConnectionStateChanged(bool connected)
        {
            this.Dispatcher.Invoke(() =>
            {
                ConnectSta.Content = connected ? "已连接" : "未连接";
                ConnectSta.Foreground = connected ? Brushes.Green : Brushes.Red;
                this.spStudent.Visibility = connected ? Visibility.Visible : Visibility.Collapsed;
            });
        }


        private void Read()
        {
            string LineName = System.Configuration.ConfigurationManager.AppSettings["LineName"].ToString();

            var DicDevType = Device_TypeDAL.GetDeviceType().ToDictionary(t => t.Id, t => t.DeviceType);
            var DevList = DeviceDAL.GetDevice();
            var DevStateList = Device_StateDAL.GetAll();
            //获取步骤列表
            OperateitemList = operateitem.GetOperateItems();
            foreach (var k in DicDevType)
            {
                DeviceList.Add(k.Key, DevList.FindAll(p => p.DeviceTypeId == k.Key && (p.LineName == LineName || p.LineName == "None")));

                DeviceStateList.Add(k.Key, DevStateList.FindAll(p => p.DeviceTypeId == k.Key));
            }

            var mytemp = DevList.Where(T => T.DeviceTypeId == 5).ToList();
            temp = mytemp;
        }

        private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
        }

        private void DockPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void WindowMin_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void WindowClose_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxButton msgbutton = MessageBoxButton.OKCancel;
            MessageBoxResult result = System.Windows.MessageBox.Show("是否退出程序？", "提示", msgbutton, MessageBoxImage.Question);
            switch (result)
            {
                case MessageBoxResult.OK:
                    this.Close();
                    break;
                case MessageBoxResult.Cancel:
                    break;
            }
        }

        private void WindowMax_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
        }

        private void ToolButton_Click(object sender, RoutedEventArgs e)
        {
            var menu = e.Source as ToolButton;
            if (menu.Tag == null) return;
            (VisualTreeHelper.GetParent(menu) as StackPanel).Children.OfType<ToolButton>().ToList().ForEach(p => p.IsSelected = false);
            menu.IsSelected = true;

            this.LoadMenuInfo(menu);
        }

        public void LoadMenuInfo(ToolButton menu, params object[] args)
        {
            try
            {
                Modules.Values.ToList().ForEach(p => p.Visibility = Visibility.Collapsed);
                Type t = Type.GetType("ET.ScoreTeacherClient.Views." + menu.Tag.ToString());//获得类型
                if (menu.MenuName == "指令编辑" || menu.MenuName == "场景管理")
                {

                    WinPWD winPWD = new WinPWD();
                    winPWD.ShowDialog();
                    if (winPWD.DialogResult == false) return;
                }
                if (Modules.ContainsKey(menu.MenuName))
                    Modules[menu.MenuName].Visibility = Visibility.Visible;
                else
                {
                    var userControl = Activator.CreateInstance(t) as UserControl;
                    this.LayOut.Children.Add(userControl);
                    Modules.Add(menu.MenuName, userControl);

                }
                (Modules[menu.MenuName] as UserControl).Tag = args;
                this.PageTitle.MenuName = menu.MenuName;
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        private async void BtnExit_Click(object sender, RoutedEventArgs e)
        {

        }

        private void BtnStart_Click(object sender, RoutedEventArgs e)
        {

        }


        private void btnScore_Click(object sender, RoutedEventArgs e)
        {
        }

        private void btnExitQuestion_Click(object sender, RoutedEventArgs e)
        {
            new EndQuestion().ShowDialog();
        }
        /// <summary>
        /// 开始培训 Add by lukun
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnTrain_Click(object sender, RoutedEventArgs e)
        {

        }
        string key2 = string.Format("{0}", "LightRgb");
        /// <summary>
        /// 结束培训 Add by lukun
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BtnOver_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxButton msgbutton = MessageBoxButton.OKCancel;
            MessageBoxResult result = System.Windows.MessageBox.Show("是否终止评测？", "提示", msgbutton, MessageBoxImage.Question);
            if (result != MessageBoxResult.OK)
                return;

        }
        /// <summary>
        /// 侧边抽屉效果方法 Add by gy
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonOpenMenu_Click(object sender, RoutedEventArgs e)
        {
            ButtonOpenMenu.Visibility = Visibility.Collapsed;
            ButtonCloseMenu.Visibility = Visibility.Visible;
        }
        private void ButtonCloseMenu_Click(object sender, RoutedEventArgs e)
        {
            ButtonCloseMenu.Visibility = Visibility.Collapsed;
            ButtonOpenMenu.Visibility = Visibility.Visible;
        }

        private void shezhi_Click(object sender, RoutedEventArgs e)
        {
            ConfigSetter configSetter = new ConfigSetter();
            configSetter.Show();
            //StepSequenceDiagramView view = new StepSequenceDiagramView(101, "79dd");
            //view.Show();
        }

        private void Checked(object sender, RoutedEventArgs e)
        {
            MissionChecked = true;
        }

        private void unChecked(object sender, RoutedEventArgs e)
        {
            MissionChecked = false;
        }
    }
}
